import {BigInteger, CryptoJS, SM2Cipher} from "./sm2-all";

function decrypt(target, priKey,cipherMode = "0") {
    let prvkey = priKey;
    let encryptData = target;
    let privateKey = new BigInteger(prvkey, 16);
    let cipher = new SM2Cipher(cipherMode);
    let data = cipher.Decrypt(privateKey, encryptData);
    return data;
}

function encrypt(target, pubKey,cipherMode="0") {
    let curve = "sm2";
    let msg = target;
    let msgData = CryptoJS.enc.Utf8.parse(msg);

    let pubkeyHex = pubKey;
    if (pubkeyHex.length > 64 * 2) {
        pubkeyHex = pubkeyHex.substr(pubkeyHex.length - 64 * 2);
    }

    let xHex = pubkeyHex.substr(0, 64);
    let yHex = pubkeyHex.substr(64);
    let cipher = new SM2Cipher(cipherMode);
    let userKey = cipher.CreatePoint(xHex, yHex);
    msgData = cipher.GetWords(msgData.toString());
    let encryptData = cipher.Encrypt(userKey, msgData);
    return encryptData;
}

const SM2Util = {
    decrypt,
    encrypt
}
export default SM2Util